package com.czk.gulimall.product.exception;

import com.czk.common.exception.BizCodeEnum;
import com.czk.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一全局异常处理
 * 集中处理异常
 *
 * @Author:ChenZhangKun
 * @Date: 2021/12/15 21:36
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.czk.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    /**
     * 处理表单校验异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException ex) {
        log.error("【数据校验出现问题{}，异常类型{}】", ex.getMessage(), ex.getClass());
        BindingResult bindingResult = ex.getBindingResult();
        if (bindingResult.hasErrors()) {
            Map<String, Object> map = new HashMap<>();
            // 获取错误结果
            bindingResult.getFieldErrors().forEach(fieldError -> {
                // 获取到错误提示，自定义的也可以是默认的
                String defaultMessage = fieldError.getDefaultMessage();
                // 获取错误的属性
                String field = fieldError.getField();
                map.put(field, defaultMessage);
            });
            return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
        }
        return R.error();
    }

    /**
     * 处理抛出的异常
     *
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable throwable) {
        throwable.printStackTrace();
        return R.error();
    }
}
